from fastapi import APIRouter, Body, Depends, Query
from fastapi.responses import HTMLResponse
from peewee_async import Manager

from common.g.g import G_REDIS, G_LOGGER, G_CLIENT
from common.pkg.ali.client import AliClient
from common.pkg.fastapi_util import cbv
from common.route.tenant_route import ClientTenantBaseAPIRoute
from common.utils.depends.common import get_mgw
from common.utils.resp import JsonResponse, RC
from core.view import ClientBaseView
from enums.pay_enum import PayWayThirdCodeEnum, PayWayTypeEnum
from schema.inner_use_schema.ali_pay_schema import AliPayPageRequestModel, AliPayAppRequestModel, AliPayWapRequestModel
from schema.req_schema.pay_schema import GetPayResourceModel
from service.order_sercice import OrderService
from service.pay_way_service import TenantPayConfigService

router = APIRouter(prefix="/pay", tags=["client_pay"], route_class=ClientTenantBaseAPIRoute)
demo_router =  APIRouter(prefix="/pay", tags=["client_pay"])


@cbv(router)
class PaymentView(ClientBaseView):

    @router.post("/order", description="根据订单获取支付链接")
    async def get_order_pay_link(self,
                                 req_model: GetPayResourceModel = Body(...)):
        oss = OrderService(self.mgw, self.redis)
        ok, data_or_code = await oss.get_order_info_for_pay(req_model.order_sn)
        if not ok:
            return JsonResponse(code=data_or_code.code, msg=data_or_code.msg).to_response()
        order = data_or_code.data
        data = dict(total_amount=order.get_should_pay_amount(),
                    subject=order.order_summary,
                    out_trade_no=order.order_sn
                    )

        if req_model.third_code == PayWayThirdCodeEnum.ali:
            tpcs = TenantPayConfigService(self.mgw, self.redis)
            ok, data_or_code = await tpcs.get_tenant_ali_pay_config(self.tenant_id)
            if not ok:
                return JsonResponse(code=data_or_code.code, msg=data_or_code.msg).to_response()
            client = AliClient(client=G_CLIENT, **data_or_code.data)

            if req_model.pay_way == PayWayTypeEnum.ali_page_pay:
                ok, res = await client.page_pay(AliPayPageRequestModel(**data))
                if ok:
                    return HTMLResponse(res)
                return JsonResponse(code=RC.INTER_ERROR, msg="服务异常", exception_track=res)
            elif req_model.pay_way == PayWayTypeEnum.ali_wap_pay:
                res = await client.wap_pay(AliPayWapRequestModel(**data))
            elif req_model.pay_way == PayWayTypeEnum.ali_app_pay:
                res = await client.app_pay(AliPayAppRequestModel(**data))
            else:
                G_LOGGER.error(f"不支持的支付方式")
                return JsonResponse(code=RC.INTER_ERROR, msg="服务异常").to_response()


@demo_router.get("/order", description="根据订单获取支付链接")
async def get_order_pay_link(
        mgw: Manager = Depends(get_mgw),
        order_sn: str = Query(...)
):
    req_model: GetPayResourceModel = GetPayResourceModel(**{
        "pay_way": 1,
        "order_sn": order_sn
    })
    tenant_id = 1000000
    oss = OrderService(mgw, G_REDIS)
    ok, data_or_code = await oss.get_order_info_for_pay(req_model.order_sn)
    if not ok:
        return JsonResponse(code=data_or_code.code, msg=data_or_code.msg).to_response()
    order = data_or_code.data
    data = dict(total_amount=order.get_should_pay_amount(),
                subject=order.order_summary,
                out_trade_no=order.order_sn
                )

    if req_model.third_code == PayWayThirdCodeEnum.ali:
        tpcs = TenantPayConfigService(mgw, G_REDIS)
        ok, data_or_code = await tpcs.get_tenant_ali_pay_config(tenant_id)
        if not ok:
            return JsonResponse(code=data_or_code.code, msg=data_or_code.msg).to_response()
        client = AliClient(client=G_CLIENT, **data_or_code.data)

        if req_model.pay_way == PayWayTypeEnum.ali_page_pay:
            ok, res = await client.page_pay(AliPayPageRequestModel(**data))
            if ok:
                return HTMLResponse(res)
            return JsonResponse(code=RC.INTER_ERROR, msg="服务异常", exception_track=res)
        elif req_model.pay_way == PayWayTypeEnum.ali_wap_pay:
            res = await client.wap_pay(AliPayWapRequestModel(**data))
        elif req_model.pay_way == PayWayTypeEnum.ali_app_pay:
            res = await client.app_pay(AliPayAppRequestModel(**data))
        else:
            G_LOGGER.error(f"不支持的支付方式")
            return JsonResponse(code=RC.INTER_ERROR, msg="服务异常").to_response()


